<template>
  <div class="appointment-page">
    <div class="page-header">
      <h2 class="page-title">我的预约</h2>
      <!-- 状态筛选 -->
      <el-radio-group v-model="currentStatus" class="status-filter">
        <el-radio-button :label="-1">全部</el-radio-button>
        <el-radio-button :label="0">待确认</el-radio-button>
        <el-radio-button :label="1">已确认</el-radio-button>
        <el-radio-button :label="2">已完成</el-radio-button>
        <el-radio-button :label="3">已取消</el-radio-button>
      </el-radio-group>
    </div>

    <!-- 预约列表 -->
    <div class="appointment-list" v-loading="loading">
      <el-card v-for="item in filteredAppointments" :key="item.id" class="appointment-card">
        <div class="card-header">
          <div class="room-info" @click="goToRoomDetail(item?.roomId)" >
            <el-image
                :src="item.roomImageUrl"
                fit="cover"
                class="room-image"
            >
              <template #error>
                <div class="image-placeholder">
                  <el-icon><Picture /></el-icon>
                </div>
              </template>
            </el-image>
            <div class="room-details">
              <h3 class="room-title">{{ item.roomName || '未知房源' }}</h3>
              <p class="room-price">￥{{ item.roomPrice || 0 }}/月</p>
            </div>
          </div>
          <div class="appointment-status">
            <el-tag :type="getStatusType(item.status)">
              {{ getStatusText(item.status) }}
            </el-tag>
          </div>
        </div>

        <div class="appointment-info">
          <div class="info-item">
            <el-icon><Calendar /></el-icon>
            <span>预约时间：{{ item.time }}</span>
          </div>
          <div class="info-item">
            <el-icon><Phone /></el-icon>
            <span>联系电话：{{ item.phone }}</span>
          </div>
          <div class="info-item">
            <el-icon><ChatLineRound /></el-icon>
            <span>备注信息：{{ item.remark || '无' }}</span>
          </div>
          <div class="info-item">
            <el-icon><Timer /></el-icon>
            <span>创建时间：{{ formatTime(item.createTime) }}</span>
          </div>

          <div class="info-item" v-if="item.status === 3">
            <el-icon><ChatLineRound /></el-icon>
            <span>取消原因：{{ item.cancelReason || '无' }}</span>
          </div>
        </div>

        <!--取消预约-->
        <div class="card-actions">
          <!-- 待确认状态可以取消预约 -->
          <el-button 
            v-if="item.status === 0"
            type="danger" 
            plain
            @click="showCancelDialog(item.id)"
          >
            取消预约
          </el-button>
          <el-button
              v-if="item.status === 0 & data.user.role === 'owner'"
              type="success"
              plain
              @click="handleConfirmAppointment(item.id)"
          >
            确认预约
          </el-button>
        </div>


        
      </el-card>

      <!-- 空状态 -->
      <el-empty
          v-if="!filteredAppointments.length"
          description="暂无预约记录"
      />
    </div>


    
    <!-- 取消预约对话框 -->
    <el-dialog
      v-model="cancelDialog.visible"
      title="取消预约"
      width="500px"
    >
      <el-form :model="cancelDialog.form" ref="cancelFormRef" :rules="cancelRules">
        <el-form-item 
          label="取消原因" 
          prop="reason"
          :label-width="'100px'"
        >
          <el-input
            v-model="cancelDialog.form.reason"
            type="textarea"
            :rows="3"
            placeholder="请输入取消预约的原因"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelDialog.visible = false">取消</el-button>
          <el-button type="primary" @click="handleCancelSubmit" :loading="cancelDialog.loading">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>

</template>

<script setup>
import {ref, computed, onMounted, reactive} from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { Calendar, Phone, ChatLineRound, Timer, Picture } from '@element-plus/icons-vue';
import dayjs from 'dayjs';
import request from '@/utils/request';

const data = reactive({
  user:JSON.parse(localStorage.getItem('localStorageUser')),
})
const router = useRouter();
const loading = ref(false);
const appointments = ref([]);
const currentStatus = ref(-1);

//取消预约对话框数据
const cancelDialog = reactive({
  visible: false,
  loading: false,
  form: {
    id: null,
    reason: ''
  }
});

// 取消表单校验规则
const cancelRules = {
  reason: [
    { required: true, message: '请输入取消原因', trigger: 'blur' },
    { min: 2, max: 200, message: '长度在 2 到 200 个字符', trigger: 'blur' }
  ]
};

const cancelFormRef = ref(null);

// 根据状态筛选预约
const filteredAppointments = computed(() => {
  if (currentStatus.value === -1) {
    return appointments.value;
  }
  return appointments.value.filter(item => item.status === currentStatus.value);
});

// 获取预约列表
const getAppointments = async () => {
  loading.value = true;
  try {
    const res = await request.get('/appointment/selectAll');
    if (res.code === '200') {
      appointments.value = res.data;
    }
  } catch (error) {
    console.log('获取预约列表失败:',error);
    ElMessage.error('获取预约列表失败');
  } finally {
    loading.value = false;
  }
};

// 显示取消预约对话框
const showCancelDialog = (id) => {
  cancelDialog.form.id = id;
  cancelDialog.form.reason = '';
  cancelDialog.visible = true;
};

// 确认预约
const handleConfirmAppointment = async (id) => {

    const res = await request.put(`/appointment/confirm?id=${id}`);
    if (res.code === '200') {
      ElMessage.success('预约已确认');
      getAppointments(); // 刷新列表
    } else {
      ElMessage.error(res.msg)
      getAppointments();
    }

}

// 提交取消预约
const handleCancelSubmit = async () => {
  if (!cancelFormRef.value) return;

  await cancelFormRef.value.validate(async (valid) => {
    if (valid) {
      cancelDialog.loading = true;
      try {
        const res = await request.put(`/appointment/cancel?id=${cancelDialog.form.id}&cancelReason=${encodeURIComponent(cancelDialog.form.reason)}`);
        if (res.code === '200') {
          ElMessage.success('预约已取消');
          cancelDialog.visible = false;
          getAppointments(); // 刷新列表
        } else {
          ElMessage.error(res.msg);
          getAppointments();
        }
      } catch (error) {
        ElMessage.error('取消预约失败');
      } finally {
        cancelDialog.loading = false;
      }
    }
  });
};

// 跳转到房间详情
const goToRoomDetail = (roomId) => {
  if (!roomId) {
    ElMessage.error('房间ID不存在');
    return;
  }
  console.log('MyAppointments 跳转到房间详情，roomId:', roomId, '类型:', typeof roomId);

  router.push({ 
    name: 'room_detail', 
    params: { roomId: roomId }
  });
};



// 格式化时间
const formatTime = (time) => {
  return dayjs(time).format('YYYY-MM-DD HH:mm');
};

// 获取状态类型
const getStatusType = (status) => {
  const types = {
    0: 'warning',//待确认
    1: 'primary',//已确认
    2: 'success',//已完成
    3: 'info'//已取消
  };
  return types[status] || 'info';
};

// 获取状态文本
const getStatusText = (status) => {
  const texts = {
    0: '待确认',
    1: '已确认',
    2: '已完成',
    3: '已取消'
  };
  return texts[status] || '未知状态';
};

onMounted(() => {
  getAppointments();
});
</script>

<style scoped>
.appointment-page {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.page-title {
  margin: 0;
  font-size: 24px;
  color: #333;
}

.status-filter {
  margin-bottom: 20px;
}

.appointment-card {
  margin-bottom: 20px;
  border-radius: 12px;
  transition: all 0.3s;
}

.appointment-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.room-info {
  display: flex;
  align-items: center;
  gap: 16px;
  cursor: pointer;
}

.room-image {
  width: 120px;
  height: 80px;
  border-radius: 8px;
  overflow: hidden;
}

.image-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f7fa;
  color: #909399;
}

.room-details {
  flex: 1;
}

.room-title {
  margin: 0 0 8px;
  font-size: 16px;
  color: #333;
}

.room-price {
  margin: 0;
  color: #ff4d4f;
  font-size: 16px;
  font-weight: 500;
}

.appointment-info {
  padding: 16px 0;
  border-top: 1px solid #eee;
  border-bottom: 1px solid #eee;
}

.info-item {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
  color: #666;
}

.info-item:last-child {
  margin-bottom: 0;
}

.info-item .el-icon {
  font-size: 16px;
  color: #909399;
}

.card-actions {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }

  .status-filter {
    width: 100%;
    overflow-x: auto;
    white-space: nowrap;
    padding-bottom: 8px;
  }

  .room-info {
    flex-direction: column;
    align-items: flex-start;
  }

  .room-image {
    width: 100%;
    height: 160px;
  }
}
</style>